<template>
	<view>
		<uni-popup ref="reserve" type="bottom" borderRadius="16rpx 16rpx 0 0" @maskClick="maskClick" :safeArea="false">
			<view class="carListBox" @touchmove.stop.prevent="" :class="{'padding-top-xs':!cartmsg}" :style="{paddingBottom:props.isPhonex? (props.uSource!='searchMenu'?'300rpx':'200rpx') : (props.uSource!='searchMenu'?'270rpx':'200rpx')}">
				<view v-if="cartmsg" class="top_tips">
					<view>
						{{cartmsg||''}}
						<!-- <text class="tip_left">已享</text> -->
						<!-- {{carlistDetial.coupons}} -->
						<!-- <text class="tip_right">优于折扣</text> -->
					</view>
				</view>
				<view class="uints">
					<view class="units_left">已选商品</view>
					<!-- （打包费<text class="text-nred">¥{{carlistDetial.packagFee}}</text>） -->
					<view class="units_left flex align-center" @click="clearCar"> <text
							class="fcon-a-Frame427320510 text-df text-bold text-c9 margin-right-xxs"></text>清空购物车
					</view>
				</view>
				<scroll-view scroll-y="true" class="fullw" style="max-height:570rpx;">
					<view class="p_rlt">
						<view v-for="(item,index) in cartList" :key="index" class="shoplists">
							<!-- 套餐 -->
							<block v-if="item.type=='dp'">
								<view class="flex">
									<view class="shop_img">
										<tb-image width="120rpx" height="120rpx" borderRadius="8rpx"
											:src="imgBaseUrl+(item.specImageUrl?item.specImageUrl:item.imageUrl)">
											<template v-slot:error>
												<image src="../../../static/menuEmpty.png" class="cimg" mode="aspectFill">
												</image>
											</template>
										</tb-image>
										<view class="shop_vip_ico" v-if="item.vipGoods">
											<text class="fcon-cvip hs_s"></text>
										</view>
										<!-- <view class="shop_empty">
												<view class="empty_invs">-</view>
												<view class="empty_text">
													售罄
													库存不足
													已下架
												</view>
												<view class="empty_invs">-</view>	
										 </view> -->
										 <!-- 特价 -->
										 <!-- <view class="tejia" v-if="item.activityType=='243'">
										 	 <text class="fcon-Vector1 spcPrice_icons"></text>
										 </view> -->
									</view>
									<view class="shop_text">
										<view class="flex justify-between padding-left-xs">
											<view class="shopName shopNameMaxw">{{ item.nameLabel||''}}</view>
											<!-- <view class="point" @click="editDp(item)">修改</view> -->
										</view>
										<view class="shopTags">
											<!-- <view class="tags_item">{{item.sellAttrCode}}</view>
											<view class="tags_item" v-for="(it,inds) in item.labels" :key="inds">{{it.name}}</view> -->
										</view>
										<view class="shop_bottom padding-left-xs">
											<view class="shop_price"><text style="font-size:20rpx">¥</text>{{ item.totalPrice||0}}
												<!-- <text v-if="item.price.costPrice!=item.totalSellPrice" class="oldPri">¥{{item.totalSellPrice||0}}</text> -->
											</view>
											<uni-number-box v-model="item.nums" nstash :min="0" :max="99" :allowInput="true" @getEvn="addClick($event, item,'addmeals')" @delEvn="reduceClick($event, item,'delmeals')" />
										</view>
									</view>
								</view>
								<view class="mealbox margin-top-sm sanjiao">
									<view v-for="(citem,cindex) in item.goodsDetails" :key="cindex">
										<view class="titname flex align-center">
											<view class="flex-sub">
												{{citem.goodsName||''}}
											</view>
											<view v-if="citem.nutrient" class="flex-sub">
												{{citem.nutrient.energy||0}}Kcal
											</view>
											<view class="">
												x{{citem.buyNums||0}}
												<!-- <uni-number-box v-model="citem.buyNums" nstash :min="0"
													:max="citem.stockTotalNums" :allowInput="true"
													@getEvn="addClick($event, item,'addsubmeal')" @delEvn="reduceClick($event, item,'delsubmeal')" /> -->
											</view>
										</view>
										<view class="spcbx padding-top-xs text-sm text-c9">
											<view v-if="citem.sellAttrCode" class="d_ib spcitm padding-lr-xs">{{citem.sellAttrCode}}</view>
											<view class="d_ib spcitm padding-lr-xs" v-for="(it,inds) in citem.labels" :key="inds">{{it.name}}</view>
											<!-- <view class="d_ib spcitm padding-lr-xs">
												小小份(100g)
											</view>
											<view class="d_ib spcitm padding-lr-xs">
												小小份(100g)
											</view>
											<view class="d_ib spcitm padding-lr-xs">
												小小份(100g)
											</view> -->
										</view>
									</view>
								
								</view>
							</block>
							<!-- 单品 -->
							<view v-else class="flex">
								<view class="shop_img">
									<tb-image width="120rpx" height="120rpx" borderRadius="8rpx"
										:src="imgBaseUrl+(item.specImageUrl?item.specImageUrl:item.imageUrl)">
										<template v-slot:error>
											<image src="../../../static/menuEmpty.png" class="cimg" mode="aspectFill">
											</image>
										</template>
									</tb-image>
									<view class="shop_vip_ico" v-if="item.vipGoods">
										<text class="fcon-cvip hs_s"></text>
									</view>
									<view class="shop_empty" v-if="0">
											<view class="empty_invs">-</view>
											<view class="empty_text">
												<!-- 售罄 -->
												库存不足
												<!-- 已下架 -->
											</view>
											<view class="empty_invs">-</view>	
									 </view>
									 <view class="tejia" v-if="item.activityType=='243'">
									 	 <text class="fcon-Vector1 spcPrice_icons"></text>
									 </view>
								</view>
								<view class="shop_text">
									<view class="flex justify-between padding-left-xs">
										<view class="shopName" :style="{color:1?'':'#999'}">{{ item.goodsName||''}}</view>
										<view class="delShop point" @click="handelDelShop(item)"><text class="fcon-a-close" v-if="0"></text></view>
									</view>
									<view class="shopTags">
										<view v-if="item.sellAttrCode" class="tags_item">{{item.sellAttrCode}}</view>
										<view class="tags_item" v-for="(it,inds) in item.labels" :key="inds">{{it.name}}
										</view>
									</view>
									<view class="shop_bottom padding-left-xs">
										<view class="shop_price" :style="{color:1?'':'#999'}"><text style="font-size:20rpx">¥</text>{{ item.activiyPrice?item.activiyPrice:item.sellPrice}}
											<text class="oldPri">¥{{item.activiyPrice?item.sellPrice:item.nold_price}}</text>
										</view>
										<uni-number-box v-model="item.buyNums" nstash :min="0"
											:max="item.stockTotalNums" :allowInput="true"
											@getEvn="addClick($event, item,'addNum')" @delEvn="reduceClick($event, item,'delNum')" />
									</view>
								</view>
							</view>
							
						</view>
					</view>

				</scroll-view>
			</view>

		</uni-popup>
		<view class="ballShow">
			<carShow ref="ballRef" :duration="700" :size="30" />
		</view>
	</view>
</template>
				
<script setup lang="ts">
	import { ref, computed } from 'vue';
	import carShow from '@/uni_modules/lime-ball/components/l-ball/l-ball.vue'
	import { showLoading, hideLoading, mnavTo, toSupFixed, trailingThrottle } from '@/utils/helper';
	import { getCartList, editCart, clearCart, shopcartDel, confirmCart, getActiveTags, deliveryCalc,editMealCart } from '@/api/vmeitime-http/index.js'
	import { useCartStore } from '@/stores/cartStore';
	import { useShopStore } from '@/stores/shopStore';
	import { useUserStore } from '@/stores/commonStore';
	// import { storeToRefs } from 'pinia';
	import { env } from '@/api/env.js'
	import mapi from '@/utils/mapi';
	const cartStore = useCartStore();
	const userStore = useUserStore();
	const shopStore = useShopStore();
	// const { actions } = storeToRefs(useCartStore());
	// const { setCartList,setCartNum } = actions;
	const props = defineProps({
		couponDis: {
			type: Object,
			default: () => {
				return {
					money: 0
				};
			},
		},
		getVCoupons: Function || null,
		getCoupons: Function || null,
		vipDis: {
			type: Object,
			default: () => {
				return { money: 0 };
			},
		},
		isPhonex:{
			type:Boolean,
			default:false
		},
		uSource:{
			type:String,
			default:''
		}
	});
	const emit = defineEmits(["maskClick", "change", "parentChange", "carNumChanges","closeModal","clearCloseModal"])
	const reserve = ref()
	const ballRef = ref()
	const imgBaseUrl = ref(env.imgBaseUrl)
	// const orderDetail = ref()
	const orderDetail = ref<any>({});//订单详细信息
	const cartList = ref([])
	const carlistDetial = ref({
		coupons: "90减23",//满减
		packagFee: "3.4",//打包费
		carList: []
	})
	const rcoupParam = ref<any>({});//代金券请求参数
	const loaded = ref(false);
	const totalCNums = ref(0);//券总数
	const open = () => {
		reserve.value.open()

		loaded.value ? reserve.value.open() : initCar('open');

		// getCarLists()
	}
	const carriages = ref<any>({ loaded: false, money: 0 })
	
	const initCar = (source : any = '') => {
		return new Promise(async (resolve, reject) => {
			try {
				source == 'open' && showLoading()
				let ndata : any = {};
				(orderDetail.value && orderDetail.value.vipCredCoupon && vipSelects.value.allowVipTotalPrice > 0 && vipSelects.value.disVAmout <= 0) ? ndata.vipCredCoupon = '6' : '';

				if (cartStore.curOrderType && cartStore.curOrderType.type) {
					ndata.patten = cartStore.curOrderType.type;
					ndata.subsTime = cartStore.curOrderType.time.dateString
				}
				let res = await confirmCart(ndata);
				if (res.result && res.object) {
					loaded.value = true;
					let nres = res.object || {}, goodsGroups = nres.goodsGroups || [], nlist = [],dynamicGoods = nres.dynamicGoods || [];
					goodsGroups.forEach(item => {
						item.goods && item.goods.length > 0 ? nlist = nlist.concat(item.goods) : '';
					})
					console.log(res.object,"nresss")
					nlist = nlist.concat(dynamicGoods);
					getNewCarList(nlist);
					orderDetail.value = nres;
					cartList.value = nlist;
					getActTags();//满减提示
					vipSelects.value = getVipDetail();//初始化vip专区券
					// console.log('initCar0000', couponsMethods)
					console.log(vipSelects.value,"vipSelects.value")
					hideLoading();
					console.log('initCar0000', source,nlist.length)
					if(source=='clear'||nlist.length<=0){
						clearClose()
					}
					
						
					if (!carriages.value.loaded || userStore.changeDCarriages) {
						let cres = await getCarriage(source);
						userStore.setDCarriages(false)
						carriages.value.money = cres || 0;
					}
					// if (source != 'change') {
						getGoodsCollect();
						let cres = await props.getCoupons(rcoupParam.value.rcoupGoods, 'init');
						couponSelects.value = cres || {};
						console.log('couponSelects', cres);
					// }
					totalCNums.value = (ndata.vipCredCoupon!='6'?nres.credCouponsTotalNums || 0:0);// + 代金券：(couponSelects.value.nums || 0)
					// orderDetail.value.credCouponsTotalNums
					(source == 'open'||source=='addCars' || source=='orderDetials'||source=='addTCars') && reserve.value.open();
					let r = calcTotal();
					resolve(r)
				} else {
					loaded.value = false;
					hideLoading()
					resolve('');
					mapi.msg(res.shortMessage || '网络繁忙，请稍后再试!', res.code)
				}
			} catch (e) {
				console.error(e)
				loaded.value = false;
				reject(e);
				hideLoading()
				mapi.msg('网络繁忙，请稍后再试!')
			}
		});
	}
	// 配送费
	const getCarriage = (source : any = '') => {
		return new Promise(async (resolve, reject) => {
			
			try {
				if (shopStore.costPlan != '1131' || !userStore.curSelecAdress.naddress_id) {
					resolve(0);
					return
				}
				let delvParam = {
					receiver_phone: userStore.curSelecAdress.vphone,
					receiver_name: userStore.curSelecAdress.vname,
					receiver_address: userStore.curSelecAdress.adrs,
					receiver_longitude: userStore.curSelecAdress.longitude,
					receiver_latitude: userStore.curSelecAdress.latitude
					// time
				}
				source === 'change' && showLoading()
				let dres = await deliveryCalc(delvParam);
				let carriage = dres.result && dres.object ? Number(dres.object || 0) : 0;
				carriages.value.loaded = dres.result ? true : false;
				source === 'change' && hideLoading()
				resolve(carriage)
			} catch (e) {
				source === 'change' && hideLoading()
				resolve(0);
				reject(e);
			}
		});
	}

	// 专区券
	const getVipDetail = () => {
		const odt = orderDetail.value;
		let redEnv = shopStore.changeCoups&&shopStore.changeCoups.length>0?shopStore.changeCoups.find((item:any) => item.id == '1'):[]
		let nlist = odt.credCouponGroups || [];

		let num = 0,
			allTotalMoney = 0,
			totalMoney = 0,
			amout = 0,
			sList = [];
		if(redEnv&&redEnv.list){
			redEnv.list.forEach(item => {
				allTotalMoney += item.faceMoney * item.storeNums
				item.selectNums > 0 && odt.vipCredCoupon ? (num += item.selectNums) : "";
				item.selectNums > 0 && odt.vipCredCoupon ? (totalMoney += item.faceMoney * item.selectNums) : "";
				if (item.selectNums > 0) {
					item.selectNums && sList.push(item)
				}
			});
		}else{

			nlist.forEach(item => {
				allTotalMoney += item.faceMoney * item.storeNums
				item.selectNums > 0 && odt.vipCredCoupon ? (num += item.selectNums) : "";
				item.selectNums > 0 && odt.vipCredCoupon ? (totalMoney += item.faceMoney * item.selectNums) : "";
				if (item.selectNums > 0) {
					item.selectNums && sList.push(item)
				}
			});
		}
	console.log(sList,"sList")
		// odt.vipCredCoupon
		let slc = {
			totalNum: odt.credCouponsTotalNums || 0,
			sList: sList,
			canUse: odt.vipCredCoupon && odt.totalVipBackPrice > 0,
			title: '已选VIP专区券使用明细',
			totalMoney: totalMoney,//专区券总金额 同allowVipTotalPrice
			disVAmout: odt.vipCredCoupon&&sList.length>0 ? odt.totalVipBackPrice || 0 : 0,
			allTotalMoney: allTotalMoney,
			allowVipTotalPrice: totalMoney,
			totalVipPrice: odt.totalVipPrice||0//vip商品总额
			// canDisAmout:amout
		};
		return slc
	}
	const cartmsg = ref('')
	//获取提示tags
	const getActTags = async () => {
		// if(!orderDetail.value.totalManPrice){
		// 	return
		// }
		try {
			const res = await getActiveTags({ money: orderDetail.value.totalManPrice || 0, ziTiBillCheck: false })
			const nres = res.object || [];
			const info = nres[0] || {};
			cartmsg.value = info.message || '';

			cartStore.setCartTags(cartmsg.value)
		} catch (e) {
			cartStore.setCartTags('')
			cartmsg.value = '';
		}
	}
	const changeCoupons = (e : any) => {
		console.log('carChangecoup0', e)
		let { curVCoupon, curCoupon } = e.value
		let needRfresh = vipSelects.value.disVAmout != curVCoupon.disVAmout;
		couponSelects.value = curCoupon || {};//已选券
		vipSelects.value = curVCoupon || {};//专区券
		console.log('carChangecoup', couponSelects.value,needRfresh)
		needRfresh ? initCar('change') : calcTotal()


	}
	//处理代金券等参数
	const getGoodsCollect = () => {
		// {sku:nsku,amount:namount,isVipGood:goodsItem.vipSellPrice?true:false}
		let skuList = [], adAmount, vipDisMoney = 0;//vipDisMoney暂++
		let isUseVip = true	//是否用专区券，暂+++  
		cartList.value.forEach((cItem, cIndex) => {
			let cateItemPrice = 0;
			let actItemPrice = 0;
			cateItemPrice = (cItem.activiyPrice ? cItem.activiyPrice : cItem.sellPrice) || 0;
			cateItemPrice = cateItemPrice * cItem.buyNums || 0;
			actItemPrice = orderDetail.value.totalManBackPrice > 0 && cItem.billActivityComputer ?
				(cItem.nowTotalMoney > 0 ? cItem.nowTotalMoney : 0) : cateItemPrice || 0;
			let namount = Number((actItemPrice).toFixed(2)) || 0;
			let skuMs = {
				sku: cItem.sku || '',
				amount: namount
				// isVipGood: cItem.vipSellPrice ? true : false
			}
			if (isUseVip && orderDetail.value.vipCredCoupon && vipDisMoney > 0) {
				!cItem.vipSellPrice && skuList.push(skuMs)
			} else {
				skuList.push(skuMs)
			}
		});
		// - this.submitData.integralTotalMoney 
		adAmount = orderDetail.value.totalPrice - vipDisMoney - (orderDetail.value.vipCredCoupon && vipDisMoney > 0 ?
			(orderDetail.value.totalVipPrice || 0 + orderDetail.value.totalVipBackPrice || 0) : 0);
		rcoupParam.value = {
			// singleData
			rcoupGoods: { manjianAmount: orderDetail.value.totalManBackPrice || 0, sku: JSON.stringify(skuList), orderAmount: (adAmount >= 0 ? adAmount : 0).toFixed(2) }//代金券请求参数
		}
	}
	// 计算
	const calcTotal = () => {
		const odt = orderDetail.value;
		let totalPrice = Number(odt.totalPrice || 0),
			ctotalBackPrice = Number(odt.totalBackPrice || 0),
			carriage = shopStore.costPlan=='1131'?Number(carriages.value.money):0,//Number(odt.carriage || 0)
			coupUseMoney = 0,//待 代金券能使用金额
			canUseVip = vipSelects.value.canUse&&odt.vipCredCoupon,//待
			vipCanBackMoney = odt.totalVipBackPrice || 0,//vip专区券可抵金额
			totalEnergy = odt.totalEnergy || 0,
			totalProtein = odt.totalProtein || 0,//蛋白质
			totalEdibleOil = odt.totalEdibleOil || 0,//油
			totalSalt = odt.totalSalt || 0,//盐
			totalFat = odt.totalFat||0;//脂肪-暂
		coupUseMoney = getRealCoupMoney();
		// couponSelects.value.realMoney = coupUseMoney
		let totalPayPrice = totalPrice - coupUseMoney - vipSelects.value.disVAmout + carriage;
		let totalBackPrice = ctotalBackPrice + coupUseMoney - (canUseVip && vipCanBackMoney > 0 && vipSelects.value.disVAmout <= 0 ? vipCanBackMoney : 0);
		let enyRate = ((totalEnergy>800?800:totalEnergy)/800).toFixed(2);
		
		let r = {
			totalPrice: totalPrice,
			totalPayPrice: toSupFixed(totalPayPrice<0?0:totalPayPrice, 2),
			totalSellerPrice: odt.totalSellerPrice || 0,
			totalManBackPrice: odt.totalManBackPrice || 0,
			carriage: carriage,
			totalBackPrice: toSupFixed(totalBackPrice, 2),// 总优惠
			list: newCarList,
			nums: cartTotalNums.value,//数量
			disVAmout: vipSelects.value.disVAmout,//vip优惠金额
			vipAllTotalMoney: vipSelects.value.allTotalMoney,//vip专区券总金额
			vipAllowTotalPrice: vipSelects.value.allowVipTotalPrice,//vip可用商品总额totalVipPrice
			totalVipPrice: vipSelects.value.totalVipPrice,//vip商品总额
			coupUseMoney: coupUseMoney,
			coupUsed: couponSelects.value.usable,//couponSelects.value.usable是否可用代金券-暂无用
			totalEnergy: totalEnergy,
			totalProtein: totalProtein,
			totalEdibleOil: totalEdibleOil,
			totalSalt: totalSalt,
			totalFat:totalFat,
			enyRate:enyRate,
			totalCoupsNums:  totalCNums.value + (coupUseMoney>0?couponSelects.value.nums:0),
			loaded: true,
			stapleFood: orderDetail.value.stapleFood,
			cartmsg:cartmsg.value



		}
		// submitData.value.totalPrice = totalPayPrice;
		// submitData.value.totalPayPrice = totalPayPrice;
		// submitData.value.carriage = carriage;
		// submitData.value.totalBackPrice = totalBackPrice;
		// submitData.value.totalSellerPrice = odt.totalSellerPrice || 0;
		console.log('cpt+++++++++++++', r);

		emit('change', r)
		return r

	}
	// ---------------------------------------------------------
	const vipSelects = ref<Record<string, any>>({
		totalNum: 0,
		sList: [],
		canUse: false,
		totalMoney: 0,
		disVAmout: 0,
		allTotalMoney: 0
	})//专区券选中
	const couponSelects = ref<Record<string, any>>({})//代金券选中


	// 代金券实际金额
	const getRealCoupMoney = () => {
		let coupUseMoney = 0;//代金券可用金额
		const voucher = couponSelects.value, odt = orderDetail.value, goods = cartList.value, couMoney = voucher.money || 0;
		const canUseVip = vipSelects.value.canUse && odt.vipCredCoupon, disVAmout = vipSelects.value.disVAmout || 0;
		let totalPrice = Number(odt.totalPrice || 0), totalVipPrice = odt.totalVipPrice || 0, vipCanBackMoney = odt.totalVipBackPrice || 0;
		let noCouponPayMoney = totalPrice - (canUseVip && disVAmout > 0 ? totalVipPrice + vipCanBackMoney : 0);//代金券不能抵扣运费、以及使用vip专区券抵扣金额
		noCouponPayMoney<0?noCouponPayMoney = 0:'';
		// couponSelects = {
		// 	type: item.coupon_type || '',
		// 	type_two: item.coupon_type_two || '',
		// 	cId: item.ncoupon_id || '',
		// 	mId: item.nmber_conpon_id || '',
		// 	money: item.ncoupon_money || 0,
		// 	sellCategory: item.sellCategory || '',
		// 	disRate: item.par_value,
		// realMoney:0,//实际使用金额 
		// skus:[]
		// }

		if (voucher.type == '865') { //是否使用专属券isSingleCoupon
			// that.isSingleCoupon = false //待+
			let nowSingleTotalMoney = 0; //使用专属券的商品实际价值总额
			var goodsArr = [];
			goodsArr = goods.filter((goodsItem : any) => {
				if (voucher.skus && voucher.skus.length > 1) {
					for (let c = 0; c < voucher.skus.length; c++) {
						let couponSku = voucher.skus[c];
						if (goodsItem.sku == couponSku) {
							return goodsItem.sku == couponSku;
						}
					}
				} else {
					let couponSku = voucher.skus[0] || 1;
					return goodsItem.sku == couponSku;
				}
			})
			let singItem = goodsArr[0] || {};
			let singGoodPrice = canUseVip && disVAmout > 0 && singItem.vipSellPrice > 0 ? 0 : singItem.activiyPrice ? singItem.activiyPrice * singItem.buyNums : singItem.sellPrice * singItem.buyNums || 0;
			odt.totalManBackPrice > 0 && singItem.billActivityComputer ? (nowSingleTotalMoney = canUseVip && disVAmout > 0 ? singItem.nowTotalMoney || 0 : singItem.fullNowTotalMoney || 0) : nowSingleTotalMoney = singGoodPrice || 0;
			// 积分7--
			// 折扣
			if (voucher.type_two == '970') {
				(voucher.cId && nowSingleTotalMoney > 0) ? coupUseMoney = toSupFixed(((1 - voucher.disRate) * nowSingleTotalMoney), 2) : coupUseMoney = 0;
				// that.isDiscount == '';
				console.log('coupon_券优惠06');
			} else {
				console.log('coupon_券优惠05');
				voucher.cId && (couMoney > nowSingleTotalMoney) ? (nowSingleTotalMoney > noCouponPayMoney ? coupUseMoney =
					noCouponPayMoney : coupUseMoney = nowSingleTotalMoney) : coupUseMoney = couMoney;
				console.log('goodsArr-singGoodItem', goodsArr, singItem, nowSingleTotalMoney, coupUseMoney);
			}
		} else if (voucher.sellCategory && voucher.sellCategory.length > 0) {//类目券
			let sellCategoryArr = voucher.sellCategory.split(',') || [];
			// let totalMaxIntegralMoney = 0; //类目商品可抵扣积分总额1++
			// let cateInteList = [];
			let nowSingleTotalMoney = 0; //使用类目券的商品实际价值总额
			let categoryGoods = [];
			sellCategoryArr.forEach(cateItem => {
				for (let k = 0; k < odt.goodsGroups.length; k++) {
					let goodsGroupItem = odt.goodsGroups[k];
					let listItemgd = goodsGroupItem.goods.filter(goodsItem => {
						return (goodsItem.sellCategoryOne == cateItem ||
							goodsItem.sellCategoryTwo == cateItem ||
							goodsItem.sellCategoryThree == cateItem);
					})
					categoryGoods = categoryGoods.concat(listItemgd);
				}
			})
			console.log('goodsList', categoryGoods)
			let hash = {};
			let newGoodsList = categoryGoods.reduce((preVal, curVal) => {
				console.log('categoodsList-reduce', canUseVip, disVAmout, (canUseVip &&
					disVAmout > 0 ? curVal.nowTotalMoney || 0 : curVal.fullNowTotalMoney || 0))
				if (!hash[curVal.sku]) {
					hash[curVal.sku] = true;
					let cateGoodPrice = canUseVip && disVAmout > 0 && curVal.vipSellPrice > 0 ? 0 :
						curVal.activiyPrice ? curVal.activiyPrice * curVal.buyNums : curVal.sellPrice * curVal.buyNums || 0;
					// nowSingleTotalMoney商品能参与代金券计算实际总金额 商品参与满减活动且使用vip专区券时取nowTotalMoney，不使用vip专区券取fullNowTotalMoney
					odt.totalManBackPrice > 0 && curVal.billActivityComputer ?
						nowSingleTotalMoney += (canUseVip && disVAmout > 0 ? (curVal.nowTotalMoney || 0) : (curVal.fullNowTotalMoney || 0)) :
						nowSingleTotalMoney += cateGoodPrice || 0;
					console.log('nowSingleTotalMoney00', nowSingleTotalMoney, odt.totalManBackPrice, curVal.billActivityComputer)
					preVal.push(curVal);
				}
				return preVal
			}, [])
			// totalMaxIntegralMoney = Number(totalMaxIntegralMoney.toFixed(2));
			nowSingleTotalMoney = Number(nowSingleTotalMoney.toFixed(2));
			console.log('nowSingleTotalMoney01', nowSingleTotalMoney)
			console.log('类目券', categoryGoods)
			// console.log('同类目商品newgoodsList', newGoodsList)
			//nowSingleTotalMoney实际券可抵扣金额（商品实际价值-商品积分实际抵扣金额）
			console.log('nowSingleTotalMoney-类目商品实际抵扣积分总额totalMaxIntegralMoney222', nowSingleTotalMoney)
			if (voucher.type_two == '970') {
				console.log('coupon_券优惠04');
				(voucher.cId && nowSingleTotalMoney > 0) ? coupUseMoney = toSupFixed(((1 - voucher.disRate) * nowSingleTotalMoney), 2) : coupUseMoney = 0;
				// that.isDiscount == ''
			} else {
				voucher.cId && (couMoney > nowSingleTotalMoney) ? (nowSingleTotalMoney > noCouponPayMoney ? coupUseMoney =
					noCouponPayMoney : coupUseMoney = nowSingleTotalMoney) : coupUseMoney = couMoney;
				console.log('coupon_券优惠03', nowSingleTotalMoney);
			}

		} else {
			// 折扣券-全场
			if (voucher.type_two == '970') {
				(voucher.cId && noCouponPayMoney > 0) ? coupUseMoney = toSupFixed(((1 - voucher.disRate) * noCouponPayMoney), 2) : coupUseMoney = 0;
				// that.isDiscount == '';
				console.log('coupon_券优惠02');
			} else {
				voucher.cId && (couMoney > noCouponPayMoney) ? coupUseMoney = noCouponPayMoney : coupUseMoney = couMoney;
				console.log('coupon_券优惠01');
			}
		}
		console.log('coupon_券优惠000', coupUseMoney, noCouponPayMoney, voucher.disRate, (1 - voucher.disRate) * noCouponPayMoney, 'vsm', vipCanBackMoney, disVAmout, (vipCanBackMoney > 0 &&disVAmout <= 0 ? vipCanBackMoney : 0));
		return Number(coupUseMoney.toFixed(2)) || 0; //代金券
	}

	// -------------------------------
	// 目标数组类型定义
	interface goodItem {
		sku : string;
		name : string;
		num : any;
		goods_id : any,
		type : any
		
	}
	// 目标数组
	const newCarList : goodItem[] = [];
	const cartTotalNums = ref(0);
	// 复制属性的函数
	const getNewCarList = (list : any) => {
		// 使用map遍历源数组，并复制特定属性
		newCarList.length = 0; // 清空目标数组
		let nums = 0;
		list.map((item : any) => {
			// 根据需要复制的属性创建新对象
			let skus:any=[];
			if(item.type=='dp'){
				let goodsList = item.goodsDetails||[];
				goodsList.forEach(citem=>{
					skus.push({
						num:citem.buyNums||0,
						sku:citem.sku||''
					})
				})
				
			}
			const newItem : goodItem = {
				name: item.goodsName||item.nameLabel||'', // 假设我们想要复制name属性，并在目标对象中命名为nickname
				sku: item.type=='dp'?skus:item.sku||'', // 假设这是我们要静态赋值的属性
				num: item.buyNums||item.nums,
				goods_id: item.goodsId||item.id,
				type:item.type||'sp'
				// 其他属性...
			};
			nums += (item.buyNums||item.nums || 0);
			return newCarList.push(newItem); // 将新对象添加到目标数组
		});
		cartTotalNums.value = nums;
		cartStore.setCartList(newCarList);
		cartStore.setCartNum(nums || 0);

		// console.log('getnewCarList', cartStore.getCartList);

	}

	// const getCarLists = async () => {
	// 	showLoading()
	// 	try {
	// 		let res = await getCartList()
	// 		if (res.result) {
	// 			carlistDetial.value.carList = res.object.goods || []
	// 			hideLoading()
	// 		}
	// 	} catch (e) {
	// 		hideLoading()
	// 		mapi.msg('网络繁忙，请稍后再试!')
	// 	}
	// }
	const maskClick = (e : any) => {
		// cartStore.$reset()
		// console.log('car-maskClick',e);
		emit("maskClick")
	}
	const close = () => {
		reserve.value.close()
		emit("closeModal")
	}
	const clearClose=()=>{
		reserve.value.close()
		emit("clearCloseModal")
	}
	const clearCar = () => {
		uni.showModal({
			title: '提示',
			content: '确定清空当前购物车么',
			confirmText: '确定',
			confirmColor: '#2AB05E',
			success: async res => {
				if (res.confirm) {
					try {
						showLoading()
						let params : any = {}
						cartStore.curOrderType && cartStore.curOrderType.type ? params.patten = cartStore.curOrderType.type : ''
						let res = await clearCart(params)
						if (res.result) {
							initCar('clear')
							emit("carNumChanges")
							shopStore.setChangeCoups([])
						} else {
							mapi.msg(res.shortMessage || '网络繁忙，请稍后再试!', res.code)
							hideLoading()
						}
					} catch (e) {
						hideLoading()
						mapi.msg('网络繁忙，请稍后再试!')
					}

				}
			}
		})
	}

	const getChangeNum = (sku : any, newNum : any,source:any='') => {
		let list = cartStore.getCartList,oldnum = 0;
		let index = list.findIndex(item => item.sku == sku)
		oldnum = index >= 0 ? list[index].num : 0
		// if(source=='sp'){
		
		// }else {
		// 	// 添加套餐编辑数量
		// }
		

		return Math.abs((newNum - oldnum))
	}

	const addCar = (e : any, item : any,source:any='') => {
		source=='addsubmeal'||source=='addmeals'?numsMealActions(e, item, source):numsActions(e, item, source);//-新增
	}
	const delCar = (e : any, item : any,source:any='') => {
		if (source=='delNum'&&item.buyNums == 0||source!='delNum'&&item.nums==0) {
			delShopCar(item)
			return
		}
		source=='delsubmeal'||source=='delmeals'?numsMealActions(e, item, source):numsActions(e, item, source);//-新增
		// numsActions(e, item, source)

	}
	const delShopCar = async (item : any) => {
		// sp :单品，tc:套餐, dp:随心配
		let params:any={
			sku: item.sku||item.id,
		}
		if(item.type=='dp'){
			params.type='dp'
		}
		let res = await shopcartDel(params)//item.id套餐ID-新增
		emit("carNumChanges")

	}
	// 编辑套餐数量
	const numsMealActions = async (e : any, item : any, types : any,source:any='') => {
		showLoading()
		try {
			// let num = getChangeNum(item.id, item.nums,source)
			console.log(item,"itemitem")
			const params:any = {
				id:item.seq,
				dynamic_id: item.id,//随心配套商品 id
				nums: 1,
				// nums: item.nums,
				act:types=='addmeals'?'addNum':'delNum',
				details: []
			};
			params.details=item.goodsDetails&&item.goodsDetails.map((items:any)=>{
				let labelIdsArray = items.labels ? items.labels.map((item : any) => item.id) : []
				return{
					sku:items.sku,
					nums:items.buyNums,
					labelIds:labelIdsArray,
					dynamic_conver_group_id:items.sxpGroupId
				}
			})
			// const params : any = item.isVip == '1' ? { ...baseParams, special_id: item.specialId } : { ...baseParams };
			if (cartStore.curOrderType && cartStore.curOrderType.type) {
				params.patten = cartStore.curOrderType.type;
				params.subsTime = cartStore.curOrderType.time.dateString
			}
			showLoading();
			let res = await editMealCart(params);
			hideLoading()
			if (res && res.result) {
					if (types == 'addNum'||types=='addsubmeal'||types=='addmeals') {
						ballRef.value.action(e.events, env.FileUrl + item.imageUrl)
					}
				emit("carNumChanges",'carlist')
				
			} else {
				if(types=='addmeals'){
					item.nums=item.nums-1
				}else{
					item.nums=item.nums+1
				}
				
				mapi.msg(res.shortMessage || "加入购物车失败!", res.code)
			
			}
		} catch (e) {
			console.error(e)
			hideLoading()
			mapi.msg('网络繁忙，请稍后再试.')
		}
	}
	const numsActions = async (e : any, item : any, types : any) => {
		// console.log('numsActions',item)
		showLoading()
		try {
			let num = getChangeNum(item.sku, item.buyNums,'sp')
			let labelIdsArray = item.labels ? item.labels.map((item : any) => item.id) : []
			let params : any = {
				sku: item.sku,
				act: types,
				nums: num,
				labelIds: labelIdsArray
			}
			if (cartStore.curOrderType && cartStore.curOrderType.type) {
				params.patten = cartStore.curOrderType.type;
				params.subsTime = cartStore.curOrderType.time.dateString
			}
			let res = await editCart(params)
			hideLoading()
			if (res.result) {
				if (types == 'addNum') {
					ballRef.value.action(e.events, env.FileUrl + item.imageUrl)
				}
				emit("carNumChanges",'carlist')
			}else{
				item.buyNums=item.buyNums-num
				mapi.msg(res.shortMessage||'网络繁忙，请稍后再试..')
			}
		} catch (e) {
			console.error(e)
			hideLoading()
			mapi.msg('网络繁忙，请稍后再试.')
		}
	}
	const handelDelShop=async(item:any)=>{
			uni.showModal({
				title: '提示',
				content: '确定删除当前商品么',
				confirmText: '确定',
				confirmColor: '#2AB05E',
				success: async res => {
					if (res.confirm) {
						try {
							showLoading()
							let res = await shopcartDel({ sku: item.sku||item.id })//item.id套餐ID-新增
							if (res.result) {
								emit("carNumChanges")
								mapi.msg("删除成功!")
							} else {
								mapi.msg(res.shortMessage || '网络繁忙，请稍后再试!', res.code)
								hideLoading()
							}
						} catch (e) {
							hideLoading()
							mapi.msg('网络繁忙，请稍后再试!')
						}
			
					}
				}
			})
			
	}
	const editDp=(item:any)=>{
		mnavTo('/pages/order/singleMeal/singleMeal?goodsId=' + item.id)
		console.log(item,"itemmm")
	}
	const addClick = trailingThrottle(addCar, 300);
	const reduceClick = trailingThrottle(delCar, 300);

	defineExpose({ open, close, initCar, changeCoupons })
</script>

<style lang="scss" scoped>
	.carListBox {
		width: 100vw;
		padding-bottom: 270rpx;//160 +110 140
		background-color: #fff;
		border-radius: 20rpx 20rpx 0rpx 0rpx;
		&.ipx{
			padding-bottom: 300rpx;//160 +110
		}
		.top_tips {
			width: 100vw;
			height: 68rpx;
			border-radius: 20rpx 20rpx 0rpx 0rpx;
			background: #FEF9E3;
			color: #FA871C;
			font-family: "Microsoft YaHei UI";
			font-size: 28rpx;
			font-weight: 400;
			line-height: 68rpx;
			text-align: center;

			.tip_left {
				color: #333;
				margin-right: 20rpx;
			}

			.tip_right {
				color: #333;
				margin-left: 20rpx;
			}
		}

		.uints {
			width: 100vw;
			height: 50rpx;
			margin-top: 15rpx;
			display: flex;
			justify-content: space-between;
			line-height: 40rpx;
			padding: 0rpx 20rpx 0rpx 20rpx;

			.units_left {
				color: #333;
				font-family: "Microsoft YaHei UI";
				font-size: 24rpx;
				font-style: normal;
				font-weight: 400;
			}
		}

		.shoplists {
			width: 100vw;
			min-height: 190rpx;
			border-top: 2rpx solid #F2F2F2;
			padding: 30rpx 20rpx 20rpx 20rpx;

			.shop_img {
				width: 120rpx;
				height: 120rpx;
				position: relative;
				.tejia{
					position: absolute;
					right:0;
					top:0;
					border-radius: 0px 4px 0px 13px;
					background: linear-gradient(90deg, #FF7A00 -10.89%, #FCDCBF 138.82%);
					width:72rpx;
					height: 36rpx;
					text-align: center;
					line-height:36rpx;
					.spcPrice_icons {
						font-size: 22rpx;
						color: #fff;
					}
				}
			.shop_empty{
				    width: 100%;
				    height:100%;
				    position: absolute;
				    top:0;
				    left: 0;
				    z-index: 9;
						background-color: rgba(0, 0, 0, 0.7);
				    border-radius: 10rpx;
				    display: flex;
				    justify-content: center;
				    align-items: center;
				    color: #FFF;
				    .empty_text{
				    	font-size: 24rpx;
				    	font-weight: 400;
				    	margin: 0 10rpx;
				    	width: 50rpx;
							color: #FFF;
				    	// margin: 0 6rpx;
				    	// width: 75rpx;
				    }
				    .empty_invs{
				    	font-size: 28rpx;
				    }
				}
				.shop_vip_ico {
					position: absolute;
					right: 0;
					bottom: 0rpx;
					z-index: 8;
					width: 36rpx;
					height: 36rpx;
					line-height: 37rpx;
					background-color: #F5A623;
					border-radius: 10rpx 0rpx 20rpx 0rpx;
					display: flex;
					justify-content: center;
					align-items: center;

					.hs_s {
						color: #fff;
						font-size: 24rpx;
						display: block;
						padding-left: 4rpx;
						// padding-top: 4rpx;
					}
				}

				.cimg {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}
			}

			.shop_text {
				width: 590rpx;
				min-height: 140rpx;
				padding-left: 20rpx;

				.shopName {
					color: #000;
					font-family: "Microsoft YaHei UI";
					font-size: 32rpx;
					font-weight: 400;
				}
       .delShop{
				 font-size: 26rpx;
				 color:#000;
			 }
				.shop_price {
					color: #FC4C40;
					font-family: "Microsoft YaHei UI";
					font-size: 32rpx;
					font-weight: 700;
					margin-right: 11rpx;
					margin-top: 17rpx;
					.oldPri{
						color: #999;
						font-size: 24rpx;
						font-weight: 400;
						text-decoration: line-through;
					}
				}

				.shop_bottom {
					width: 100%;
					height: 46rpx;
					display: flex;
					justify-content: space-between;
					position: relative;
				}
			}

			.shopTags {
				width: 100%;
				min-height: 40rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				flex-wrap: wrap;

				.tags_item {
					min-width: 88rpx;
					height: 44rpx;
					border-radius: 10rpx;
					background: rgba(235, 239, 251, 0.50);
					margin-left: 10rpx;
					color: #999;
					font-size: 28rpx;
					font-weight: 400;
					text-align: center;
					line-height: 44rpx;
					margin-top: 15rpx;
					padding: 0 20rpx 0 20rpx;
				}
			}
		}
	}

	.mealbox {
		border-radius: 10rpx;
		background: #FAFAFA;
		min-height: 70rpx;
		padding: 5rpx 0 5rpx 16rpx;

		.titname {
			padding: 10rpx 60rpx 0 0;
		}

		.spcitm {
			min-width: 60rpx;
			height: 40rpx;
			line-height: 41rpx;
			border-radius: 10rpx;
			background: rgba(235, 239, 251, 0.50);
			margin: 0 10rpx 10rpx 0;
		}
	}

	.ballShow {
		width: 100rpx;
		height: 40rpx;
		position: absolute;
		bottom: 40rpx;
		left: 20;
		z-index: 99;
	}
	.sanjiao {
		position: relative;
		&:before{
			content:'';
			position: absolute;
			width: 0;
			height: 0;
			align-self: center;
			position: absolute;
			border: 16rpx solid transparent;
			top: -16rpx;
			left: 45rpx;
			// margin-left: -20rpx;
			border-top: none;
			border-bottom-color: #FAFAFA;
			z-index: 1;
		}
		
	}
	.shopNameMaxw{
		max-width: 490rpx;
	}
</style>